package com.fpc.cn.springbootutil.exception;

import com.fpc.cn.springbootutil.base.BaseResponse;
import com.fpc.cn.springbootutil.base.BaseUtilService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @date 2025/4/28
 * @author fupengcheng
 * @describe 全局异常处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = {"com.fpc.cn.springbootutil"})
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private BaseUtilService baseUtilService;


    @ExceptionHandler(value = Exception.class)
    public BaseResponse exception(Exception exception) {
        log.info(exception.getMessage(), exception);
        if (exception instanceof BusinessException) {
            BusinessException businessException = (BusinessException) exception;
            return baseUtilService.setResult(businessException.getCode(),exception.getMessage(),null);
        }
        if (exception instanceof IllegalArgumentException) {
            IllegalArgumentException argumentException = (IllegalArgumentException) exception;
            return baseUtilService.setResultError(argumentException.getMessage());
        }
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            return baseUtilService.setResultError(methodArgumentNotValidException.getMessage());
        }
        return baseUtilService.setResult(10000,"未知异常",null);
    }


}
